import random


class Board:
    def __init__(self):
        self.grid = [[' ' for _ in range(3)] for _ in range(3)]
        self.movable_positions = [(i, j) for i in range(3) for j in range(3)]

    def show_board(self):
        print("\n当前棋盘状态（坐标：行号(0-2) 列号(0-2)）:")
        for i in range(3):
            print(f" {i} | {' | '.join(self.grid[i])} | {i}")
            if i < 2:
                print("---+-------+---")
        print("   0   1   2\n")

    def move_down(self, x, y, chess):
        if (x, y) not in self.movable_positions:
            return False
        self.grid[x][y] = chess
        self.movable_positions.remove((x, y))
        return True

    def is_win(self, chess):
        for i in range(3):
            if all(self.grid[i][j] == chess for j in range(3)) or \
                    all(self.grid[j][i] == chess for j in range(3)):
                return True
        if all(self.grid[i][i] == chess for i in range(3)) or \
                all(self.grid[i][2 - i] == chess for i in range(3)):
            return True
        return False

    def is_draw(self):
        return len(self.movable_positions) == 0

    def reset_board(self):
        self.grid = [[' ' for _ in range(3)] for _ in range(3)]
        self.movable_positions = [(i, j) for i in range(3) for j in range(3)]


class Player:
    def __init__(self, name, chess):
        self.name = name
        self.chess = chess
        self.score = 0

    def get_move(self, board):
        pass


class AIPlayer(Player):
    def __init__(self, name="电脑"):
        super().__init__(name, 'O')

    def get_move(self, board):

        for (x, y) in board.movable_positions:
            temp_board = [row.copy() for row in board.grid]
            temp_board[x][y] = self.chess
            if self._is_win(temp_board, self.chess):
                return (x, y)


        player_chess = 'X'
        for (x, y) in board.movable_positions:
            temp_board = [row.copy() for row in board.grid]
            temp_board[x][y] = player_chess
            if self._is_win(temp_board, player_chess):
                return (x, y)


        value_positions = [
            (1, 1),
            (0, 0), (0, 2), (2, 0), (2, 2),
            (0, 1), (1, 0), (1, 2), (2, 1)
        ]
        for pos in value_positions:
            if pos in board.movable_positions:
                return pos

        
        return random.choice(board.movable_positions)

    def _is_win(self, board, chess):
        for i in range(3):
            if all(board[i][j] == chess for j in range(3)) or \
                    all(board[j][i] == chess for j in range(3)):
                return True
        if all(board[i][i] == chess for i in range(3)) or \
                all(board[i][2 - i] == chess for i in range(3)):
            return True
        return False


class Game:
    def __init__(self):
        self.board = Board()
        self.player = Player("玩家", 'X')
        self.ai = AIPlayer()
        self.current_player = None

    def start(self):
        print("欢迎来到井字棋游戏!")
        print("玩家1: 你（X） vs 玩家2: 电脑（O）\n")

        while True:
            self._reset_round()
            self._play_round()
            if not self._ask_continue():
                break
        print("\n游戏结束，感谢参与！")

    def _reset_round(self):
        self.board.reset_board()
        self.current_player = self.player if random.randint(0, 1) == 0 else self.ai
        print(f"本局先手：{self.current_player.name}（{self.current_player.chess}）")
        self.board.show_board()

    def _play_round(self):
        while True:
            if isinstance(self.current_player, AIPlayer):
                print(f"\n{self.current_player.name}正在思考...")
                x, y = self.current_player.get_move(self.board)
            else:
                x, y = self._get_human_move()

            if not self.board.move_down(x, y, self.current_player.chess):
                print("该位置已被占据，请重新选择！")
                continue

            self.board.show_board()

            if self.board.is_win(self.current_player.chess):
                print(f"恭喜{self.current_player.name}获胜！")
                self.current_player.score += 1
                break
            if self.board.is_draw():
                print("本局和棋！")
                break

            self.current_player = self.player if self.current_player == self.ai else self.ai

    def _get_human_move(self):
        while True:
            try:
                x = int(input("请输入行坐标(0-2): "))
                y = int(input("请输入列坐标(0-2): "))
                if 0 <= x <= 2 and 0 <= y <= 2:
                    return (x, y)
                print("坐标范围应为0-2，请重新输入！")
            except ValueError:
                print("请输入有效的数字坐标！")

    def _ask_continue(self):
        print(f"\n当前比分：你 {self.player.score} : {self.ai.score} 电脑")
        while True:
            choice = input("是否继续游戏？(y/n) ").strip().lower()
            if choice == 'y':
                return True
            elif choice == 'n':
                return False
            print("请输入'y'或'n'！")


if __name__ == "__main__":
    game = Game()
    game.start()